package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    private static long tokenExpiration = 24*60 * 60 * 1000L;
    private static SecretKey tokenSignKey =
            Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes()); //秘钥
    public static String createToken(Long userId, String username) {
        String token = Jwts.builder().
                setSubject("USER_INFO").
                setExpiration(new Date(System.currentTimeMillis() +
                        tokenExpiration)).//过期时间
                claim("userId", userId).//自己的字段用claim声明
                claim("username", username).
                signWith(tokenSignKey).
                compact();
        return token;
    }

    //解析token
    public static Claims parseToken(String token){
        if (token==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try{
            JwtParser jwtParser =
                    Jwts.parserBuilder().setSigningKey(tokenSignKey).build();
            return jwtParser.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);//token过期
        }catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID); //token非法
        }
    }

    public static void main(String[] args) {
        System.out.println(JwtUtil.createToken(1L, "admin"));
    }
}